package open.witype.filetiper.fragment.file.loader;

import android.content.Context;
import android.os.AsyncTask;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import open.witype.filetiper.fragment.file.FileFragment;
import open.witype.filetiper.fragment.file.adapter.RecyclerViewAdapter;
import open.witype.filetiper.model.FileItemBean;

/**
 * Created by Typer on 2015/5/22 0022.
 * 加载文件列表的异步线程
 */
public class FileLoader extends AsyncTask<String, FileItemBean, List<FileItemBean>> {

    private FileFragment fragment;

    private OnLoaderFinish onLoaderFinish;

    public FileLoader( OnLoaderFinish onLoaderFinish) {
        this.onLoaderFinish = onLoaderFinish;
    }

    @Override
    protected List<FileItemBean> doInBackground(String... params) {
        List<FileItemBean> dirs = new ArrayList<>();
        List<FileItemBean> files = new ArrayList<>();
        String path = params[0];
        File file = new File(path);
        if (!file.exists())
            return null;
        File list[] = file.listFiles();
        for (File temp : list) {
            FileItemBean item = new FileItemBean(temp);
            if (item.getFileName().startsWith("."))
                continue;
            if (item.isFile())
                files.add(item);
            else if (item.isDirectory())
                dirs.add(item);
        }
        Collections.sort(dirs, new FileSort());
        Collections.sort(files, new FileSort());
        dirs.addAll(files);
        return dirs;
    }

    public interface OnLoaderFinish{

        void onLoadFinish(List<FileItemBean> fileItemBeans);

    }

    @Override
    protected void onPostExecute(List<FileItemBean> fileItemBeans) {
        super.onPostExecute(fileItemBeans);
        onLoaderFinish.onLoadFinish(fileItemBeans);
    }

    public class FileSort implements Comparator<FileItemBean> {
        @Override
        public int compare(FileItemBean f1, FileItemBean f2) {
            return byName(f1,f2);
        }
    }

    public int byName(FileItemBean f1, FileItemBean f2) {
        if (f1 == null || f2 == null)// 先比较null
            if (f1 == null)
                return -1;
            else
                return 1;
        else if (f1.isDirectory() && f2.isDirectory())// 再比较文件夹
            return f1.getAbsName().compareToIgnoreCase(f2.getAbsName());
        else if (f1.isDirectory() && !f2.isDirectory())
            return -1;
        else if (f2.isDirectory() && !f1.isDirectory())
            return 1;
        else
            return f1.getAbsName().compareToIgnoreCase(f2.getAbsName());// 最后比较文件
    }


}
